﻿$(function(){
    function GetBuildsDictionary(area_id, caller) {
		var area = $('#'+area_id);
		var vdiv = area_id+'Tab';

		area.html('<div id="'+vdiv+'Pager"></div><table id="'+vdiv+'"></table>');

        var el_office_id;
        var el_office_name;
        var office_name = '';
		
        var pager = $('#' + vdiv + 'Pager');
        var gritab;
        var col_order = [0, 1, 2, 3, 4];
        var col_names = ['ID', 'Шифр объекта', 'Адрес объекта', 'Офис ID', 'Офис'];
        var col_model = [
		    { name: 'id', index: 'build_id', hidden: true, width: 1, editable: false, fixed: true },
		    { name: 'build_name', index: 'build_name', hidden: false, width: 150, editable: true, 
                    editoptions: { maxlength: "64", style: "width:95%;min-width:100px;"}, formoptions: { label: '', 
					elmprefix: '<div class="jqg-form-label-up">Шифр объекта</div>'}},
		    { name: 'build_address', index: 'build_address', hidden: false, width: 300, editable: true, 
                    editoptions: { maxlength: "128", style: "width:95%;min-width:100px;"}, 
					formoptions: { label: '', elmprefix: '<div class="jqg-form-label-up">Адрес объекта</div>'} },
		    { name: 'build_office_id', index: 'build_office_id', hidden: true, width: 1, editable: true,
		        editoptions: { maxlength: "16", dataInit: function (el) { el_office_id = el; } }
		    },
		    { name: 'office_name', index: 'office_name', hidden: false, width: 150, editable: true,
		        editoptions: { maxlength: "64", style: "width:95%;min-width:100px;margin-bottom:16px;", 
				dataInit: function (el) { el_office_name = el; } },
				formoptions: { label: '', elmprefix: '<div class="jqg-form-label-up">Шифр офиса</div>'}
		    }
        ];
        var jqgo = {
            url: 'index.php',
            editurl: 'index.php',
            datatype: 'json',
            postData: { q: 'builds/index' },
            emptyrecords: true,
            autowidth: false,
            gridview: true,
            hidegrid: false,
            hoverrows: true,
            recordpos: 'right',
            scrollrows: true,
            multiselect: true,
            multiselectWidth: 40,
            multiboxonly: true,
            mtype: 'POST',
            shrinkToFit: false,
            colNames: col_names,
            colModel: col_model,
            page: 1,
            pager: pager,
            pagerpos: 'right',
            rowNum: 15,
            rowList: [15, 45, 150],
            loadui: 'disable',
            toolbar: [false, 'top'],
            filterbar: false,
            height: area.innerHeight() - 77,
            width: area.innerWidth() - 2,
            sortname: 'build_name',
            sortorder: 'asc',
            sortable: true,
            caption: '',
            loadError: function (xhr, status, error) {
                alert("Ошибка загрузки даных");
            },
            loadComplete: function (data) {
                switch( data.userdata.errcode ) {
                    case 0:
/*
                        if ($.browser.msie || $.browser.webkit) {
                            $('#' + vdiv + ' tr.jqgrow td').height(21);
                        }
*/
                        break;
                    case 999:    
                        alert("Ваша сессия закончилась по таймауту.\nПожалуйста перерегистрируйтесь.");
                        break;
                    case 99:    
                        app.alert('AlertDlg', 'Ошибка', data.userdata.errmess, 'app-icon-stop32', caller.Close );
                        break;
                    default:
                        alert( data.userdata.errmess );
                        break;
                }                
            },
            ondblClickRow: function (id) {
                $('#' + vdiv).jqGrid('editGridRow', id,
                {
                    modal: true,
                    jqModal: true,
                    zIndex: app.jqgrid_form_min_z_index,
					resize: false,
                    closeOnEscape: true,
                    savekey: [true, 13],
                    editData: { q: 'builds/update' },
                    afterShowForm: onShowEditForm,
                    afterSubmit: responseOnSubmit,
                    viewPagerButtons: false,
                    closeAfterEdit: true
                }
                );
            }
        };
        // Создадим jqGrid
        gritab = $('#' + vdiv).jqGrid(jqgo);

        // Индикация ошибок добавления, ред., удал.
        function responseOnSubmit(response, postdata) {
            var rsp = $.parseJSON(response.responseText);
            var success = true;
            var msg = '';

            if (rsp.errcode) {
                success = false;
                msg = rsp.errmess;
                if (rsp.errcode == '999') {
                    alert("Ваша сессия закончилась по таймауту.\nПожалуйста перерегистрируйтесь.");
                }
            }
            return [success, msg];
        }

// Autocomplete
		function onShowEditForm(fm) {
			SetOfficeHack();
            $('div#editmod' + vdiv).css({'overflow':'visible'}).shadow();
		}
		function onCloseEditForm() {
			$(el_office_name).autocomplete( "destroy" ).unbind();
			return true;
		}
		
		
// Навигатор
        gritab.jqGrid('navGrid', '#' + vdiv + 'Pager',
// Параметры инструментов
        {
            add: true, del: true, edit: true, search: false,
            afterRefresh: function () { gritab.resetSelection(); }
        },
// Параметры редактирования
        {
            modal: true,
            jqModal: true,
            zIndex: app.jqgrid_form_min_z_index,
			resize: false,
            savekey: [true, 13],
            closeOnEscape: true,
            editData: { q: 'builds/update' },
            afterShowForm: onShowEditForm,
            afterSubmit: responseOnSubmit,
            viewPagerButtons: false,
            closeAfterEdit: true
        },
// Параметры добавления
        {
            modal: true,
            jqModal: true,
            zIndex: app.jqgrid_form_min_z_index,
			resize: false,
            savekey: [true, 13],
            closeOnEscape: true,
            editData: { q: 'builds/insert' },
            afterShowForm: onShowEditForm,
            afterSubmit: responseOnSubmit
        },
// Параметры удаления
        {
            modal: true,
            jqModal: true,
            zIndex: app.jqgrid_form_min_z_index,
            width: 250,
			msg: '<table style="width:240px;margin-top:16px;"><tr><td style="width:50px;">'+
				'<div class="app-icon-quest32"></div></td><td>Удалить выбранную запись(и) ?</td></tr></table>',
			resize: false,
            closeOnEscape: true,
            delData: { q: 'builds/delete' },
            afterShowForm: function () {
                $('div#delmod' + vdiv).shadow();
            },
            afterSubmit: responseOnSubmit
        }
        );
        
        function SetOfficeHack() {
            $(el_office_name).autocomplete({
				html: true,
				appendTo: 'div#editmod' + vdiv,
                source: function (request, responce) {
                    $.post('index.php', { q: 'builds/find', term: request.term },
                    function (rsp, textStatus) {
                        if (rsp.errcode) {
                            if (rsp.errcode == '999') { alert(rsp.errmess); }
                            else app.alert('AlertDlg', 'Ошибка', rsp.errmess, 'app-icon-stop32');
                            responce();
                            return;
                        }
                        if (rsp.data) {
                            responce($.map(rsp.data, function (item) {
                                return { label: item.name + ' ( '+item.address+' )', 
										value:item.value, name:item.name, address:item.address }
                            }));
                            return;
                        }
                        responce();
                    }, 
                    'json');
                },
                minLength: 2, autoFocus: true,
                focus: function (event, ui) { return false; },
                select: function (event, ui) {
                    $(el_office_id).val(ui.item.value);
                    office_name = ui.item.name.replace(/<(b|\/b)>/g,'');
                    $(el_office_name).val(office_name);
                    return false;
                }
            });
			office_name = $(el_office_name).val();
            $(el_office_name).bind( 'focusout', function () { 
                if( $(el_office_name).val() != office_name ) { 
                    office_name = '';
                    $(el_office_id).val("");
                }
            });            
        }


        gritab.filterToolbar({ searchOnEnter: false, afterSearch: function () { } });

		this.Destroy = function() {
			gritab.GridDestroy(vdiv);
			area.find('*').remove();
		};
		this.Resize = function() {
			gritab.setGridWidth( area.innerWidth() - 2 );
			gritab.setGridHeight( area.innerHeight() - 77 );
		}

    };  // End of create function definition


    app.ShowBuildsDictionary = function (dlgID) {
        var oTab;
        var aldlg = $('#' + dlgID);
		var me = this;

        if ($('#' + dlgID + 'Tab').length) return;

        aldlg.dialog(
        {
            modal: false, title: 'Справочник объектов',
            height: 450, width: 684,
			closeOnEscape: true,			
            autoOpen: false,
            resizable: true,
			resize: function( e, ui ) { oTab.Resize(); },
            open: function () { 
				oTab = new GetBuildsDictionary(dlgID, me);
				$('div[aria-describedby="' + dlgID + '"]').shadow() 
			},
            close: function () {
                if (oTab) oTab.Destroy();
                aldlg.dialog("destroy");
            }
        });

		this.Close = function() { aldlg.dialog('close'); };
		
        aldlg.dialog('open');
    }
});
